#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time    : 2021/3/7 11:21 下午
# @Author  : 白辉东
# @Email   : xyxk-huidong.bai@ximalaya.com
# @File    : devicesUtils.py
# @Software: PyCharm

import os
import subprocess
import serial
import serial.tools.list_ports
import platform
from public.common.speaker_type import SpeakerType
import logging.config
from config import projectPath

# 加载配置文件
logging.config.fileConfig(projectPath.LOG_CONFIG_DIR)
logger = logging.getLogger('my_logger')


def get_adb_list():
    """
    :return: 读取adb设备列表
    """
    devices_list = []
    pop = subprocess.Popen('adb devices', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    lines = pop.stdout.readlines()
    for line in lines:
        if '\\tdevice' in str(line):
            # 编码转换，标准输出字节流转string
            log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")
            device_sn = log.split('\t')[0]
            devices_list.append(device_sn)
    return devices_list


def get_serial_list():
    """
    :return: 读取串口列表
    """
    port_list_name = []
    if platform.system() == 'Windows':
        logger.info('获取串口设备列表中，运行于Windows系统...')
        port_list = list(serial.tools.list_ports.comports())
        for each_port in port_list:
            port_list_name.append(each_port[0])
    else:
        logger.info('获取串口设备列表中，运行于非Windows系统...')
        ports = os.popen('ls /dev/tty.usbserial*').readlines()
        if len(ports):
            for p in ports:
                port_list_name.append(p[:-1])

    if not len(port_list_name):
        logger.error('获取串口设备列表失败，请检查设备...')
        return []

    logger.info('串口列表为：%s' % port_list_name)
    return port_list_name


def get_all_devices():
    """
    :return: 获取所有设备列表
    """
    serial_list = get_serial_list()
    adb_list = get_adb_list()
    return serial_list + adb_list


def get_test_speaker_info():
    """
    获取测试音箱的信息
    :return: sn音箱
    :return: speaker_type音箱设备类型
    """
    sn = ''
    devices_list = get_all_devices()
    if len(devices_list):
        sn = devices_list[0]
    speaker_type = SpeakerType.DEFAULT
    if any(key in sn for key in ['COM', '/dev/tty']):
        speaker_type = SpeakerType.NANO_RTOS
    else:
        if 'XYBK' in sn:
            speaker_type = SpeakerType.XIAOYA_BIG
        elif any(key in sn for key in ['00001041', '00001021']):
            speaker_type = SpeakerType.XIAOMEI_MINI
        elif any(key in sn for key in ['NANO0', 'NANO000', 'NANO1']):
            speaker_type = SpeakerType.NANO_MAIN
        elif any(key in sn for key in ['00001031', '00001051']):
            speaker_type = SpeakerType.XIAOMEI_BIG
        else:
            speaker_type = SpeakerType.DEFAULT
    return sn, speaker_type
